package me.shurufa.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.event.EventObject;
import me.shurufa.fragments.SearchBookFragment;
import me.shurufa.utils.Constants;
import me.shurufa.utils.StatusBarCompat;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/14 14:19
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 新建书摘本  搜索书界面， 分两种情况 一种是上个界面根据ISBN查询出来的，本界面请求显示，调用查ISBN的接口
 *                                       另一种是这个界面输入文字进行搜索  调用查询书的接口
 *
 *                                       两种情况 都是点击item进行添加，然后跳转到我的书架界面
 */
public class NewDigestBookSearchActivity extends AppCompatActivity implements View.OnClickListener {//, TextWatcher, TextView.OnEditorActionListener {

    @Bind(R.id.toolbar_title)
    TextView toolbar_title;
    @Bind(R.id.fragment_container)
    FrameLayout fragmentContainer;

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.search_edit)
    EditText searchEdit;

    @Bind(R.id.ll_search)
    LinearLayout ll_search;

    SearchBookFragment mSearchFragment;
    private int searchType = -1;
    private int mFromWhere;
    private String isbn;
    private InputMethodManager imm;
    private Handler mHandler = new Handler();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.activity_new_digest_search_book);
        StatusBarCompat.setColor(this, getResources().getColor(R.color.red_new), 0);
        ButterKnife.bind(this);
        parseArguments();
        uiInit();
        initLinstener();
    }

    public static void initArguments(Intent in, int type, int fromWhere) {
        in.putExtra(Constants.EXTRA_SEARCH_TYPE, type);
        in.putExtra(Constants.ARG_FROM_WHERE, fromWhere);
    }

    public static void initArguments(Intent in, int type, String isbn, int fromWhere) {
        in.putExtra(Constants.EXTRA_SEARCH_TYPE, type);
        in.putExtra(Constants.EXTRA_SEARCH_ISBN, isbn);
        in.putExtra(Constants.ARG_FROM_WHERE, fromWhere);
    }

    private void parseArguments() {
        searchType = getIntent().getIntExtra(Constants.EXTRA_SEARCH_TYPE, 0);
        isbn = getIntent().getStringExtra(Constants.EXTRA_SEARCH_ISBN);
        mFromWhere = getIntent().getIntExtra(Constants.ARG_FROM_WHERE, 0);
    }

    private void uiInit() {
        imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        toolbar_title.setText(getString(R.string.new_book));
        initFragment();

        if (Constants.SEARCH_BY_KEYWORD == searchType) {
            // 弹出键盘
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Utils.showSoftkeyboard(NewDigestBookSearchActivity.this, searchEdit);
                }
            }, 400);
        } else {
            ll_search.setVisibility(View.GONE);

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSearchFragment.searchByIsbn(isbn);
                }
            }, 200);
        }
    }

    /**
     * 切换搜索显示方式，用于根据关键词查询 和ISBN查询
     */
    private void initFragment() {
        //boolean isSearchByKeyword = (searchType == Constants.SEARCH_BY_KEYWORD);

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        mSearchFragment = SearchBookFragment.newInstance(Constants.FROM_SEARCH, mFromWhere);
        ft.replace(R.id.fragment_container, mSearchFragment);
        ft.commit();
    }

    private void initLinstener() {
        back.setOnClickListener(this);
        // 编辑框回车搜索
        searchEdit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 触发-搜索
                    search(searchEdit.getText().toString());
                    Utils.closeInputMethod(NewDigestBookSearchActivity.this, searchEdit);
                    // 防止-焦点下移
                    return true;
                }

                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                finish();
                break;
            case R.id.back:
                finish();
                break;
        }
    }


    public void search(String text) {

        if (TextUtils.isEmpty(text)) {
            Utils.showToast("识别失败，请重新试试");
            return;
        }

        if (text.length() == 0) {
            fragmentContainer.setVisibility(View.GONE);
            return;
        }
        mSearchFragment.search(text, mFromWhere);
    }

    /*void switchSearchType(int type) {
        if (type == searchType)
            return;
        Fragment oldFragment = null;
        if (searchType >= 0)
            oldFragment = fragments[searchType];
        searchType = type;
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (oldFragment != null)
            ft.hide(oldFragment);

        SearchFragment newFragment = fragments[searchType];
        if (newFragment == null) {
            switch (searchType) {
                case 0:
                    newFragment = SearchFragment.newInstance(Constants.SEARCH_BY_ISBN);
                    break;
                case 1:
                    newFragment = SearchFragment.newInstance(Constants.SEARCH_BY_KEYWORD);
                    break;
            }
            fragments[searchType] = newFragment;
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragment_container, newFragment, String.valueOf(searchType));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
        String text = searchEdit.getText().toString();
        if (text.length() > 0) {
            newFragment.searchKey = text;
            final SearchFragment finalNewFragment = newFragment;
//            searchEdit.postDelayed(new Runnable() {
//                @Override
//                public void run() {
                    finalNewFragment.refreshShowPtr();
//                }
//            }, 300);
        }
    }*/

    public void onEventMainThread(EventObject object) {

        /*if (object.getEventAction().equals(Constants.EVENT_STAR_BOOK)) {
            final Book book = object.getBook();
            if (Global.DEBUG)
                Utils.showToast("bookId:" + book.id + "\n" + "externalBookId:" + book.external_book_id);
            ColorDialog dialog = new ColorDialog(this);
            dialog.setAnimationEnable(true);
            dialog.setTitle(getString(R.string.add_to_shelves));
            dialog.setContentText(getString(R.string.positive_to_add));
            dialog.setPositiveListener(getString(R.string.ok), new ColorDialog.OnPositiveListener() {
                @Override
                public void onClick(ColorDialog dialog) {
                    dialog.dismiss();
                    new RequestServerTask<BaseResponse>(BaseResponse.class, NewDigestBookSearchActivity.this, getString(R.string.commit_pls_wait)) {
                        @Override
                        protected String requestServer() {
                            Map<String, Object> params = new HashMap<String, Object>();
                            LogUtils.kLog().e("bookId = " + book.id + ",externalBookId = " + book.external_book_id);
                            if (book.bid != 0L)
                                params.put("bookId", book.bid);
                            else
                                params.put("externalBookId", book.external_book_id);
                            params.put("token", Global.currentUser.token);
                            return HttpUtil.post(API.ADD_BOOK_TO_SHELVES, params);
                        }

                        @Override
                        protected void onSuccess(BaseResponse result) {
                            if (result.success) {
                                EventBus.getDefault().post(new Intent(Constants.ACTION_BOOKSHELVES_REFRESH));
                                NewDigestBookSearchActivity.this.finish();
                            }
                        }
                    }.start();
                }
            })
                    .setNegativeListener(getString(R.string.cancel), new ColorDialog.OnNegativeListener() {
                        @Override
                        public void onClick(ColorDialog dialog) {
                            dialog.dismiss();
                        }
                    }).show();
        }*/
    }

}
